from flask import request, session
from app import db
from app.models.user_behavior import UserBehavior
from flask_login import current_user

def track_user_behavior(action_type, object_id=None, object_type=None):
    """记录用户行为数据"""
    try:
        user_id = current_user.user_id if current_user.is_authenticated else None
        
        behavior = UserBehavior(
            user_id=user_id,
            action_type=action_type,
            object_id=object_id,
            object_type=object_type,
            session_id=session.get('sid', None),
            ip_address=request.remote_addr,
            user_agent=request.user_agent.string if request.user_agent else None,
            url=request.url
        )
        
        db.session.add(behavior)
        db.session.commit()
        return True
    except Exception as e:
        # 记录错误但不中断用户体验
        print(f"Tracking error: {e}")
        db.session.rollback()
        return False
